<template>
	<view>
		<view class="navbar" :style="'height: ' + (navbar.top + navbar.height + 6) + 'px;'">
			<view class="inner" :style="'padding: ' + navbar.top + 'px 90px 0 90px;'">
				<view class="scan"
					:style="'top: ' + (navbar.top + 5) + 'px;left: ' + (window.windowWidth - navbar.right + 5) + 'px;height: ' + navbar.height + 'px'"
					@tap="goBackTap">
					<view class="label">
						<van-icon size="20px" color="white" name="arrow-left" />
					</view>
				</view>
				<!-- navtext -->
				<view class="navtext" :style="'padding: ' + (navbar.height - 24) / 2 + 'px'">
					<text class="navtext_t">{{ nav_Text }}</text>
				</view>
			</view>
		</view>
		<view :style="'height: ' + (navbar.top + navbar.height + 6) + 'px;'"></view>
		<view class='news'>
			<view class="news_tab">
				<view class="news_tab_item" @tap="gotoxtchat">
					<van-icon size="20px" name="/static/img/xtxx.png" />
					<view class="ext">系统消息</view>
				</view>
				<view class="news_tab_item" @tap="sendJhPhone" v-if="ShopId > 0">
					<van-icon size="20px" name="/static/img/jhphone.png" />
					<view class="ext">交换电话</view>
				</view>
				<view class="news_tab_item" @tap="gototxl">
					<van-icon size="20px" name="/static/img/txl.png" />
					<view class="ext">通讯录</view>
				</view>
			</view>
			<!-- 消息类型-MessageType 0-消息、1-表情、2-图片、3-语音、4-交换电话、5-优惠券、6-需求卡片、7-视频 -->
			<view class="historycon">
				<scroll-view :scroll-y="true" :scroll-into-view="scrollid" :scroll-with-animation="true"
					:style="'height:' + (scrollHeight - navbar.top - navbar.height - 76) + 'px'" class="history"
					:refresher-enabled="true" @refresherrefresh="refresh" :refresher-triggered="triggered">
					<!-- 历史记录部分start -->
					<view v-if="historyList.length > 0">
						<view class="historyText">历史消息</view>
						<block v-for="(item, index) in historyList" :key="index">
							<!-- 历史消息--对方 -->

							<view v-if="item.mes_From == 'left'" :id="'historyscrollid' + index">
								<view>
									<text class="chat-time" style="display: none">{{ item.ReadTime }}</text>
								</view>
								<view class="other-record">
									<image class="other-head-img"
										:src="friend_avatarUrl != 'null' ? $com.imageOSS(friend_avatarUrl) : $com.imageOSS('abc.jpg')">
									</image>
									<view
										:class="'other-record-content-triangle ' + (item.MessageType == 5 ? 'coupon_jiao_l' : '')">
									</view>
									<!-- 交换电话/优惠券--卡片 -->
									<block
										v-if="item.MessageType == 4 || item.MessageType == 5 || item.MessageType == 6 || item.MessageType == 8">
										<view v-if="item.MessageType == 4" class="phone_card">
											<view class="phone_jh_title">
												<view>对方请求您的电话号码，</view>
												<view>是否同意？</view>
											</view>
											<view class="phone_jh_btn" v-if="!item.isAgree">
												<view class="ty_btn jhphone_btn" @tap="agreePhone"
													:data-msgno="item.MsgNo">同意</view>
												<view class="bty_btn jhphone_btn" @tap="refusePhone"
													:data-msgno="item.MsgNo">拒绝</view>
											</view>
											<view v-else class="isagree_btn">已{{ item.isAgree == 1 ? '同意' : '拒绝' }}交换电话
											</view>
										</view>
										<view v-if="item.MessageType == 5" class="coupon_msg">
											<view class="coupon_info">
												￥
												<text class="pic">{{ item.Msg.price }}</text>
											</view>
											<view class="coupon_center">
												<view class="coupon_info_num">{{ item.Msg.name }}</view>
												<view class="coupon_info_date">截止：{{ item.Msg.endtime }}</view>
											</view>
											<view class="rt" :data-msgno="item.MsgNo"
												@tap="parseEventDynamicCode($event, item.Msg.isreceived ? '' : 'linquCoupon')">
												<van-button round plain size="small" type="danger"
													:color="item.Msg.isreceived ? '#999' : ''">
													{{ item.Msg.isreceived ? '已领取' : '领取' }}
												</van-button>
											</view>
										</view>
										<view v-if="item.MessageType == 6" class="xuqiu_msg" @tap="goxuqiuDetai"
											:data-xqid="item.Msg.id">
											<view class="xuqiu_picurl">
												<image class="xuqiu_pic_img" :src="$com.imageOSS(item.Msg.picurl)">
												</image>
											</view>
											<view class="xuqiu_info">
												<view class="xuiqu_title ellipsis">{{ item.Msg.title }}</view>
												<view class="xq_ava_name">
													<image class="xuqiu_headurl" :src="$com.imageOSS(item.Msg.headurl)">
													</image>
													<view class="xuiqu_name ellipsis">{{ item.Msg.nickname }}</view>
												</view>
											</view>
										</view>
										<view v-if="item.MessageType == 8" class="product_msg"
											@tap="goproductdetail(item.Msg.id)">
											<view class="product_title">亲，我要咨询商品底价</view>
											<view class="product_box">
												<view class="product_picurl">
													<image class="product_pic_img"
														:src="$com.imageOSS(item.Msg.picurl)"></image>
												</view>
												<view class="product_info">
													<view class="info_title ellipsis">{{ item.Msg.title }}</view>
													<!-- #ifdef MP-WEIXIN -->
													<view class="info_title ellipsis">原价：{{ item.Msg.price }}元</view>
													<!-- #endif -->
												</view>
											</view>
											<!-- #ifdef MP-WEIXIN -->
											<view class="product_dis_price">
												超低底价：<view
													:class="item.Msg.discount_price>0?'islookprice':''">
													{{item.Msg.discount_price>0?item.Msg.discount_price:'****'}}元
												</view>
											</view>
											<!-- #endif -->
											<view class="price_btn">
												<view v-if="item.Msg.discount_price<=0" class="xj_btn"
													@tap.stop.prevent="handleChajia(item.MsgNo,item.Msg.discount_price)">
													告知底价
												</view>
												<!-- <view v-else class="xj_btn xj_btn_y">已告知底价</view> -->
											</view>
										</view>
									</block>
									<view v-else class="other-record-content">
										<view v-if="item.MessageType == 0">{{ item.Msg }}</view>
										<image v-if="item.MessageType == 1" :src="item.Msg"
											style="width: 30px; height: 30px" />
										<image @tap="onPreviewImage" :data-url="item.Msg" v-if="item.MessageType == 2"
											:src="item.Msg" style="width: 100px" mode="widthFix" />
										<video v-if="item.MessageType == 7" :src="$com.imageOSS(item.Msg)" controls
											poster="" name="" author="" style="width: 200px" object-fit="cover"></video>
										<view v-if="item.MessageType == 3" @tap="onPlay" :data-url="item.Msg"
											:data-no="item.MsgNo" :data-status="item.ReadStatus" class="msg_yuyin">
											<van-icon v-if="cut_video == item.Msg" size="20px"
												name="/images/yuyin_gl.gif" />
											<van-icon v-else size="20px" name="/images/yuyin_l.png" />
											<text>{{ item.shichang }}''</text>
										</view>
									</view>
									<view class="unread_icon" v-if="!item.ReadStatus"></view>
								</view>
							</view>

							<!-- 历史消息--对方结尾 -->

							<!-- 历史消息--自己 -->

							<view :id="'historyscrollid' + index" v-else>
								<view>
									<text class="chat-time" style="display: none">{{ item.ReadTime }}</text>
								</view>
								<view class="own-record">
									<!-- 交换电话/优惠券--卡片 -->
									<block
										v-if="item.MessageType == 4 || item.MessageType == 5 || item.MessageType == 6 || item.MessageType == 8">
										<view v-if="item.MessageType == 4" class="phone_card">
											<view class="phone_jh_title">
												<view>已向对方发送交换电话请求</view>
												<view>等待对方同意</view>
											</view>
										</view>
										<view v-if="item.MessageType == 5" class="coupon_msg">
											<view class="coupon_info">
												￥
												<text class="pic">{{ item.Msg.price }}</text>
											</view>
											<view class="coupon_center">
												<view class="coupon_info_num">{{ item.Msg.name }}</view>
												<view class="coupon_info_date">截止：{{ item.Msg.endtime }}</view>
											</view>
										</view>
										<view v-if="item.MessageType == 6" class="xuqiu_msg" @tap="goxuqiuDetai"
											:data-xqid="item.Msg.id">
											<view class="xuqiu_picurl">
												<image class="xuqiu_pic_img" :src="$com.imageOSS(item.Msg.picurl)">
												</image>
											</view>
											<view class="xuqiu_info">
												<view class="xuiqu_title ellipsis">{{ item.Msg.title }}</view>
												<view class="xq_ava_name">
													<image class="xuqiu_headurl" :src="$com.imageOSS(item.Msg.headurl)">
													</image>
													<view class="xuiqu_name ellipsis">{{ item.Msg.nickname }}</view>
												</view>
											</view>
										</view>
										<view v-if="item.MessageType == 8" class="product_msg"
											@tap="goproductdetail(item.Msg.id)">
											<view class="product_title">亲，我要咨询商品底价</view>
											<view class="product_box">
												<view class="product_picurl">
													<image class="product_pic_img"
														:src="$com.imageOSS(item.Msg.picurl)"></image>
												</view>
												<view class="product_info">
													<view class="info_title ellipsis">{{ item.Msg.title }}</view>
													<!-- #ifdef MP-WEIXIN -->
													<view class="info_title ellipsis">原价：{{ item.Msg.price }}元</view>
													<!-- #endif -->
												</view>
											</view>
											<!-- #ifdef MP-WEIXIN -->
											<view class="product_dis_price">
												超低底价：<view
													:class="item.Msg.discount_price>0?'islookprice':''">
													{{item.Msg.discount_price>0?item.Msg.discount_price:'****'}}元
												</view>
											</view>
											<!-- #endif -->
										</view>
									</block>
									<view v-else class="own-record-content">
										<view v-if="item.MessageType == 0">{{ item.Msg }}</view>
										<image v-if="item.MessageType == 1" :src="item.Msg"
											style="width: 30px; height: 30px" />
										<image @tap="onPreviewImage" :data-url="item.Msg" v-if="item.MessageType == 2"
											:src="item.Msg" style="width: 100px" mode="widthFix" />
										<video v-if="item.MessageType == 7" :src="$com.imageOSS(item.Msg)" controls
											poster="" name="" author="" style="width: 200px" object-fit="cover"></video>
										<view v-if="item.MessageType == 3" @tap="onPlay" :data-url="item.Msg"
											class="msg_yuyin">
											<text>{{ item.shichang }}''</text>
											<van-icon v-if="cut_video == item.Msg" size="20px"
												name="/images/yuyin_gl.gif" style="transform: rotate(180deg)" />
											<van-icon v-else size="20px" name="/images/yuyin_r.png" />
										</view>
									</view>
									<view
										:class="'own-record-content-triangle ' + (item.MessageType == 5 ? 'coupon_jiao' : '')">
									</view>
									<image class="own-head-img"
										:src="selfAvatar != 'null' ? $com.imageOSS(selfAvatar) : $com.imageOSS('abc.jpg')">
									</image>
								</view>
							</view>

							<!-- 历史消息--自己结尾 -->
						</block>
						<view class="historyText" id="bottom">以上为历史消息</view>
					</view>
					<!-- 历史记录部分end -->

					<!-- 新消息 -->
					<block v-for="(item, index) in newsList" :key="index">
						<!-- 新消息--对方 -->

						<view v-if="item.mes_From == 'left'" :id="'scrollid' + index">
							<view>
								<text class="chat-time" style="display: none">{{ item.date }}</text>
							</view>
							<view class="other-record">
								<image class="other-head-img"
									:src="friend_avatarUrl != 'null' ? $com.imageOSS(friend_avatarUrl) : $com.imageOSS('abc.jpg')">
								</image>
								<view
									:class="'other-record-content-triangle ' + (item.MessageType == 5 ? 'coupon_jiao_l' : '')">
								</view>
								<!-- 交换电话/优惠券--卡片 -->
								<block
									v-if="item.MessageType == 4 || item.MessageType == 5 || item.MessageType == 6 || item.MessageType == 8">
									<view v-if="item.MessageType == 4" class="phone_card">
										<view class="phone_jh_title">
											<view>对方请求您的电话号码，</view>
											<view>是否同意？</view>
										</view>
										<view class="phone_jh_btn" v-if="!item.isAgree">
											<view class="ty_btn jhphone_btn" @tap="agreePhone" :data-msgno="item.MsgNo">
												同意</view>
											<view class="bty_btn jhphone_btn" @tap="refusePhone"
												:data-msgno="item.MsgNo">拒绝</view>
										</view>
										<view v-else class="isagree_btn">已{{ item.isAgree == 1 ? '同意' : '拒绝' }}交换电话
										</view>
									</view>
									<view v-if="item.MessageType == 5" class="coupon_msg">
										<view class="coupon_info">
											￥
											<text class="pic">{{ item.Msg.price }}</text>
										</view>
										<view class="coupon_center">
											<view class="coupon_info_num">{{ item.Msg.name }}</view>
											<view class="coupon_info_date">截止：{{ item.Msg.endtime }}</view>
										</view>
										<view class="rt" :data-msgno="item.MsgNo"
											@tap="parseEventDynamicCode($event, item.Msg.isreceived ? '' : 'linquCoupon')">
											<van-button round plain size="small" type="danger">
												{{ item.Msg.isreceived ? '已领取' : '领取' }}
											</van-button>
										</view>
									</view>
									<view v-if="item.MessageType == 6" class="xuqiu_msg" @tap="goxuqiuDetai"
										:data-xqid="item.Msg.id">
										<view class="xuqiu_picurl">
											<image class="xuqiu_pic_img" :src="$com.imageOSS(item.Msg.picurl)"></image>
										</view>
										<view class="xuqiu_info">
											<view class="xuiqu_title ellipsis">{{ item.Msg.title }}</view>
											<view class="xq_ava_name">
												<image class="xuqiu_headurl" :src="$com.imageOSS(item.Msg.headurl)">
												</image>
												<view class="xuiqu_name ellipsis">{{ item.Msg.nickname }}</view>
											</view>
										</view>
									</view>
									<view v-if="item.MessageType == 8" class="product_msg"
										@tap="goproductdetail(item.Msg.id)">
										<view class="product_title">亲，我要咨询商品底价</view>
										<view class="product_box">
											<view class="product_picurl">
												<image class="product_pic_img" :src="$com.imageOSS(item.Msg.picurl)">
												</image>
											</view>
											<view class="product_info">
												<view class="info_title ellipsis">{{ item.Msg.title }}</view>
												<!-- #ifdef MP-WEIXIN -->
												<view class="info_title ellipsis">原价：{{ item.Msg.price }}元</view>
												<!-- #endif -->
											</view>
										</view>
										<!-- #ifdef MP-WEIXIN -->
										<view class="product_dis_price">
											超低底价：<view
												:class="item.Msg.discount_price>0?'islookprice':''">
												{{item.Msg.discount_price>0?item.Msg.discount_price:'****'}}元
											</view>
										</view>
										<!-- #endif -->
										<view class="price_btn">
											<view v-if="item.Msg.discount_price<=0" class="xj_btn"
												@tap.stop.prevent="handleChajia(item.MsgNo,item.Msg.discount_price)">
												告知底价
											</view>
											<!-- <view v-else class="xj_btn xj_btn_y">已告知底价</view> -->
										</view>
									</view>
								</block>
								<view v-else class="other-record-content">
									<view v-if="item.MessageType == 0">{{ item.Msg }}</view>
									<image v-if="item.MessageType == 1" :src="item.Msg"
										style="width: 30px; height: 30px" />
									<image v-if="item.MessageType == 2" @tap="onPreviewImage" :data-url="item.Msg"
										:src="item.Msg" style="width: 100px" mode="widthFix" />
									<video v-if="item.MessageType == 7" :src="$com.imageOSS(item.Msg)" controls
										poster="" name="" author="" style="width: 200px" object-fit="cover"></video>
									<view v-if="item.MessageType == 3" @tap="onPlay" :data-url="item.Msg"
										:data-no="item.MsgNo" :data-status="item.ReadStatus" class="msg_yuyin">
										<van-icon v-if="cut_video == item.Msg" size="20px"
											name="/images/yuyin_gl.gif" />
										<van-icon v-else size="20px" name="/images/yuyin_l.png" />
										<text>{{ item.shichang }}''</text>
									</view>
									<view v-if="item.MessageType == 4" class="phone_card">
										<view class="phone_jh_title">
											<view>对方请求您的电话号码，</view>
											<view>是否同意？</view>
										</view>
										<view class="phone_jh_btn" v-if="!item.isAgree">
											<view class="ty_btn jhphone_btn" @tap="agreePhone" :data-msgno="item.MsgNo">
												同意</view>
											<view class="bty_btn jhphone_btn" @tap="refusePhone"
												:data-msgno="item.MsgNo">拒绝</view>
										</view>
										<view v-else class="isagree_btn">已{{ item.isAgree == 1 ? '同意' : '拒绝' }}交换电话
										</view>
									</view>
								</view>
								<view class="unread_icon" v-if="!item.ReadStatus"></view>
							</view>
						</view>

						<!-- 新消息--自己 -->

						<view :id="'scrollid' + index" v-else>
							<view>
								<text class="chat-time" style="display: none">{{ item.date }}</text>
							</view>
							<view class="own-record">
								<view style="margin-top: 20rpx; margin-right: 10rpx">
									<van-icon v-if="item.sendType == 'loading'" size="20px"
										name="/static/img/loading.png" />
									<!-- <van-icon wx:if="{{item.sendType == 'success'}}" color="green" size="20px" name="checked" /> -->
									<van-icon v-if="item.sendType == 'error'" color="red" size="20px" name="info" />
								</view>
								<!-- 交换电话/优惠券/需求--卡片 -->
								<block
									v-if="item.MessageType == 4 || item.MessageType == 5 || item.MessageType == 6 || item.MessageType == 8">
									<view v-if="item.MessageType == 4" class="phone_card">
										<view class="phone_jh_title">
											<view>已向对方发送交换电话请求</view>
											<view>等待对方同意</view>
										</view>
									</view>
									<view v-if="item.MessageType == 5" class="coupon_msg">
										<view class="coupon_info">
											￥
											<text class="pic">{{ item.Msg.price }}</text>
										</view>
										<view class="coupon_center">
											<view class="coupon_info_num">{{ item.Msg.name }}</view>
											<view class="coupon_info_date">截止：{{ item.Msg.endtime }}</view>
										</view>
									</view>
									<view v-if="item.MessageType == 6" class="xuqiu_msg" @tap="goxuqiuDetai"
										:data-xqid="item.Msg.id">
										<view class="xuqiu_picurl">
											<image class="xuqiu_pic_img" :src="$com.imageOSS(item.Msg.picurl)"></image>
										</view>
										<view class="xuqiu_info">
											<view class="xuiqu_title ellipsis">{{ item.Msg.title }}</view>
											<view class="xq_ava_name">
												<image class="xuqiu_headurl" :src="$com.imageOSS(item.Msg.headurl)">
												</image>
												<view class="xuiqu_name ellipsis">{{ item.Msg.nickname }}</view>
											</view>
										</view>
									</view>
									<view v-if="item.MessageType == 8" class="product_msg"
										@tap="goproductdetail(item.Msg.id)">
										<view class="product_title">亲，我要咨询商品底价</view>
										<view class="product_box">
											<view class="product_picurl">
												<image class="product_pic_img" :src="$com.imageOSS(item.Msg.picurl)">
												</image>
											</view>
											<view class="product_info">
												<view class="info_title ellipsis">{{ item.Msg.title }}</view>
												<!-- #ifdef MP-WEIXIN -->
												<view class="info_title ellipsis">原价：{{ item.Msg.price }}元</view>
												<!-- #endif -->
											</view>
										</view>
										<!-- #ifdef MP-WEIXIN -->
										<view class="product_dis_price">
											超低底价：<view
												:class="item.Msg.discount_price>0?'islookprice':''">
												{{item.Msg.discount_price>0?item.Msg.discount_price:'****'}}元
											</view>
										</view>
										<!-- #endif -->
									</view>
								</block>
								<view v-else class="own-record-content">
									<view v-if="item.MessageType == 0">{{ item.Msg }}</view>
									<image v-if="item.MessageType == 1" :src="item.Msg"
										style="width: 30px; height: 30px" />
									<image v-if="item.MessageType == 2" @tap="onPreviewImage" :data-url="item.Msg"
										:src="item.Msg" style="width: 100px" mode="widthFix" />
									<video v-if="item.MessageType == 7" :src="$com.imageOSS(item.Msg)" controls
										poster="" name="" author="" style="width: 200px" object-fit="cover"></video>
									<view v-if="item.MessageType == 3" @tap="onPlay" :data-url="item.Msg"
										class="msg_yuyin">
										<text>{{ item.shichang }}''</text>
										<van-icon v-if="cut_video == item.Msg" size="20px" name="/images/yuyin_gl.gif"
											style="transform: rotate(180deg)" />
										<van-icon v-else size="20px" name="/images/yuyin_r.png" />
									</view>
								</view>
								<view
									:class="'own-record-content-triangle ' + (item.MessageType == 5 ? 'coupon_jiao' : '')">
								</view>
								<image class="own-head-img"
									:src="selfAvatar != 'null' ? $com.imageOSS(selfAvatar) : $com.imageOSS('abc.jpg')">
								</image>
							</view>
						</view>

						<!-- own结尾 -->

						<view class="newText" id="bottom"></view>
					</block>
				</scroll-view>
			</view>
		</view>

		<!-- 底部工具栏 -->
		<view class="sendmessage">
			<view class="send-message">
				<!-- 语音 -->
				<view class="chat-volume">
					<van-icon v-if="!is_audio" @tap.native="bindChange_audio" size="30px"
						name="/static/images/yuyin.png" />
					<van-icon v-else size="30px" @tap.native="bindChange_text" name="/static/images/jianpan.png" />
				</view>
				<block>
					<input v-if="!is_audio" class="chat-input" type="text" @input="bindChange" @confirm="send"
						confirm-type="send" :value="inputtext" cursor-spacing="16px" :hold-keyboard="true"
						placeholder=" " />
					<view v-else :class="'chat-audio ' + (isTag ? 'is_tag' : '')" @longpress="onStartRecord"
						@touchend="onStopRecord">按住 说话</view>
				</block>

				<!-- 表情 -->
				<van-icon class="chat-emotion" @tap.native="emotionChange" color="#000" size="30px" name="smile-o" />

				<van-icon size="28px" name="add-o" color="#000" @tap.native="moreChange" />
			</view>
			<!-- 表情框 -->
			<view class="emotions" v-if="emotionVisible">
				<swiper class="emotions-swiper" :indicator-dots="true" duration="150"
					style="height: 200px; width: 100%">
					<block v-for="(page, index) in emojiList2" :key="index">
						<swiper-item>
							<view class="emotions-swiper_item">
								<block v-for="(em, index1) in page" :key="index1">
									<view class="swiper_box" @tap="addemotion" :data-index="em">
										<image style="width: 35px; height: 35px" mode="widthFix"
											:src="imageCdn + 'bq/' + em.url"></image>
									</view>
								</block>
							</view>
						</swiper-item>
					</block>
				</swiper>
			</view>
			<!-- 更多选择框 -->
			<view class="more_box" v-if="moreVisible">
				<view class="more_panel" style="height: 230px; width: 100%">
					<!-- 照片 -->
					<view class="more_item_box">
						<view class="more_item">
							<van-uploader accept="image" max-count="9" @after-read="afterRead" :deletable="true"
								multiple upload-icon="photo" preview-size="28" :preview-image="false"
								customIconClass="iblack" />
						</view>
						<view class="more_tit">照片</view>
					</view>

					<!-- 视频 -->
					<view class="more_item_box">
						<view class="more_item">
							<van-uploader accept="video" max-count="9" @after-read="afterVideoRead" :deletable="true"
								multiple upload-icon="photograph" preview-size="28" :preview-image="false"
								customIconClass="iblack" />
						</view>
						<view class="more_tit">视频</view>
					</view>
					<!-- 优惠券 -->
					<view class="more_item_box" v-if="ShopId > 0">
						<view class="more_item" @tap="sendCouponPopupBottom">
							<van-icon name="coupon" size="26px" color="#000" />
						</view>
						<view class="more_tit">发优惠券</view>
					</view>
				</view>
			</view>
			<!-- 需求卡片 -->
			<view class="xuqiu_card" v-if="isSendXuqiu">
				<image class="xuqiu_img" :src="$com.imageOSS(xuqiuObj.picurl)"></image>
				<view class="wecome">
					<view class="text_tit">刚刚浏览的笔记</view>
					<view class="text_we ellipsis">{{ xuqiuObj.title }}</view>
				</view>
				<view class="send_xq_btn" @tap="handleSendXuqiu">发送</view>
				<view @tap="closeXuqiu">
					<van-icon size="34rpx" name="cross" />
				</view>
			</view>
		</view>

		<uni-popup ref="sendCouponBotRefs" type="bottom" @close="sendCouponBotClose" background-color="#fff"
			borderRadius="40rpx 40rpx 0 0">
			<view class="ld_pop">
				<view class="ld_title">选择优惠券</view>

				<scroll-view v-if="couponList.length > 0" class="coupon_list" scroll-y>
					<block v-for="(item, index) in couponList" :key="index">
						<view class="coupon_item">
							<view class="coupon_item_info">
								￥
								<text class="item_pic">{{ item.info.price }}</text>
							</view>
							<view class="coupon_center">
								<view class="coupon_info_num item_num">{{ item.info.name }}</view>
								<view class="coupon_info_date item_date">截止：{{ item.info.endtime }}</view>
							</view>
							<view class="coupon_item_btn" :data-info="item.info" @tap="fasongCoupon">
								<view class="item_coubtn">发送</view>
							</view>
						</view>
					</block>
				</scroll-view>
			</view>
		</uni-popup>

		<uni-popup ref="setDiscountRef" type="center" :mask-click="false">
			<view class="pop_center">
				<view class="pop_centert_tit" style="text-align: left">
					设置超低底价
					<view class="poa_line"></view>
				</view>
				<view class="day_input">
					<van-cell-group :border="false" title="商品折扣价">
						<view class="iipptt">
							<uni-easyinput :inputBorder="false" type="text" v-model="setdisprice" placeholder="请输入超低底价">
							</uni-easyinput>
						</view>
					</van-cell-group>
				</view>
				<view style="padding: 100rpx 20rpx 60rpx">
					<van-button block round color="#323232" size="large" @tap.native="handleSetDisprice">确定</van-button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getImage,
		getPage,
		getTabbar,
		ChatConfig
	} from '../../utils/config'
	import api from '../../utils/api'
	import {
		http,
		storage,
		promisify,
		$toast,
		$loading,
		$query,
	} from '../../utils/utils'
	import {
		emojiLists
	} from '../../utils/emoj'
	import wxApi from '../../utils/wxApi'
	import {
		headerInfo
	} from '../../utils/env'
	let app = getApp()
	let {
		height,
		right,
		menuWidth
	} = headerInfo
	let leftStyle = `right: ${menuWidth / 2 / 2 + right}px`
	let tipTopStyle = `top: ${height}px;`
	let topStyle = `top: ${height + 10}px;`
	export default {
		data() {
			return {
				getImage: getImage,
				nav_Text: '',
				friend_avatarUrl: '',
				emojiList2: [],
				is_audio: false,
				isTag: false,
				receivebaseInfo: {},
				selfAvatar: '',
				sendAvatar: '',
				newsList: [],

				//消息列表
				historyList: [],

				inputtext: '',
				openid: null,
				emotionVisible: false,
				moreVisible: false,
				inputShowed: false,
				scrollTop: 0,
				inputBottom: '0px',
				receiveMemberId: null,
				sendMemberId: null,
				scrollid: 'bottom',
				scrollHeight: '300px',

				//  下拉刷新
				triggered: true,

				//  历史记录当前页
				pageNo: 1,

				socketOpen: false,

				// WebSocket连接状态
				socketMsgQueue: [],

				// WebSocket消息队列
				manualStop: false,

				touserid: 0,
				imageCdn: api.imageCdn,
				isKeyboard: false,
				cut_video: '',
				sendCouponShow: false,

				// 发优惠券弹窗
				couponobj: {
					orderamount: null,
					price: null,
					days: null
				},

				couponList: [],
				isSendXuqiu: false,

				xuqiuObj: {
					title: ''
				},

				shopid: '',
				userId: '',
				ShopId: '',
				getPages: '',

				navbar: {
					top: '',
					height: '',
					right: 0
				},

				window: {
					windowWidth: 0
				},

				bank_img: '',
				isShow: false,
				page: [],

				em: {
					url: ''
				},
				setdisprice: '',
				set_msgno: '',
				socket:null
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: async function(options) {
			console.log('ooo', options);
			if (JSON.stringify(options) !== '{}') {
				if (options.xuqiuInfo) {
					let xuqiuInfo = options.xuqiuInfo;
					let xuqiuObj = JSON.parse(decodeURIComponent(xuqiuInfo));
					console.log('xuqiuObj===', xuqiuObj);
					this.isSendXuqiu = true
					this.xuqiuObj = xuqiuObj
				}
				this.shopid = options.id
				this.nav_Text = options.user_name
				this.friend_avatarUrl = options.img
				this.touserid = options.touserid
				if (!this.nav_Text || !this.friend_avatarUrl) {
					const res = await http.post(api.default, {
						data: {
							action: 'getchatuserinfo',
							touserid: options.touserid
						}
					});
					this.nav_Text = res.data.data.nickname
					this.friend_avatarUrl = res.data.data.heal_url
					console.log('kkkkkkkkkkkkk', res);
				}
				this.connectWebSocket();
			}
			try {
				const res = await app.globalData.getLogin();
				console.log('getLogin()', res);
				let selfAvatar = res.data.shop?.picurl || res.data.user?.head_url || 'abc.jpg';
				this.userId = res.data.user?.user_id
				this.ShopId = res.data.shop?.ShopId || ''
				this.selfAvatar = selfAvatar
			} catch (err) {
				console.log('CatchClause', err);
				console.log('CatchClause', err);
				$toast('获取用户信息失败');
			}

			//  获取历史记录
			try {
				await this.getHistory();
			} catch (err) {
				console.log('CatchClause', err);
				console.log('CatchClause', err);
				$toast('获取消息失败');
			}

			//  获取历史记录
			try {
				await this.getshopcoupons();
			} catch (err) {
				console.log('CatchClause', err);
				console.log('CatchClause', err);
				$toast('获取优惠券失败');
			}
			var receiveMemberId = options.receiveMemberId;
			var sendMemberId = app.globalData.open_id;
			var sendAvatar = app.globalData.sendAvatar;
			var that = this;
			this.receiveMemberId = receiveMemberId
			this.sendMemberId = sendMemberId
			this.sendAvatar = sendAvatar
			//  获取内存中的数据
			this.getStorageBaseInfo();
			//  设置滚动区域的高度
			this.setScrollHeight();
			// 初始化websocket
			//this.initWebSocket()
			//  页面进入滚动到底部
			this.scrollBottom(true);

			//获取路由数量
			this.getPages = getCurrentPages().length
			/**
			 * 获取system信息
			 */
			this.emojiList2 = emojiLists
			promisify(uni.getSystemInfo)().then((res) => {
				//获取右上角胶囊信息
				this.navbar = uni.getMenuButtonBoundingClientRect()
				this.window = res
			});
		},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {
			this.uppdatereadmsg();
		},
		methods: {
			//连接WebSocket服务器

			connectWebSocket: function() {
				var that = this;
				const socket = uni.connectSocket({
					url: ChatConfig.CIM_URI,
					success: function(res) {
						console.log('WebSocket连接成功');
					},
					fail: function(res) {
						console.log('WebSocket连接失败:', res);
					}
				});
				this.socket = socket;
				
				// #ifdef MP-TOUTIAO
				socket.onOpen(function(res) {
					console.log('WebSocket连接已打开');
					that.socketOpen = true
					for (var i = 0; i < that.socketMsgQueue.length; i++) {
						that.sendSocketMessage(that.socketMsgQueue[i]);
					}
					that.socketMsgQueue = []
					that.innerOnConnectFinished();
				})
				socket.onClose(function(res) {
					console.log('WebSocket连接已关闭:', res);
					that.socketOpen = false
					// that.innerOnConnectionClosed(res);
				})
				socket.onMessage(function(res) {
					console.log('接收到服务器发送的数据:', res.data);
					that.innerOnMessageReceived(res);
					// var messages = that.data.messages
					// messages.push(res.data)
					// that.setData({
					//   messages: messages,
					//   scrollIntoView: 'message-' + messages.length
					// })
				})
				// #endif

				// #ifdef MP-WEIXIN
				uni.onSocketOpen(function(res) {
					console.log('WebSocket连接已打开');
					that.socketOpen = true
					for (var i = 0; i < that.socketMsgQueue.length; i++) {
						that.sendSocketMessage(that.socketMsgQueue[i],socket);
					}
					that.socketMsgQueue = []
					that.innerOnConnectFinished();
				});
				uni.onSocketError(function(res) {
					console.log('WebSocket连接打开失败:', res);
				});
				uni.onSocketClose(function(res) {
					console.log('WebSocket连接已关闭:', res);
					that.socketOpen = false
					// that.innerOnConnectionClosed(res);
				});
				uni.onSocketMessage(function(res) {
					console.log('接收到服务器发送的数据:', res.data);
					that.innerOnMessageReceived(res);
					// var messages = that.data.messages
					// messages.push(res.data)
					// that.setData({
					//   messages: messages,
					//   scrollIntoView: 'message-' + messages.length
					// })
				});
				// #endif
			},

			innerOnConnectFinished: function() {
				let account = '';
				if (account === '' || account === undefined) {
					this.onConnectFinished();
				} else {
					this.bindAccount(account);
				}
			},

			onConnectFinished: function() {
				//获取当前登录用户
				app.globalData.getLogin().then((res) => {
					console.log('获取当前登录用户', res);
					this.userId = res.data.user.user_id
					this.bind(res.data.user.user_id);
				});
			},

			bind: function(account) {
				storage.set('account', account);
				let deviceId = ''; //storage.get('deviceId');
				if (deviceId === '' || deviceId === undefined) {
					deviceId = this.generateUUID();
					storage.set('deviceId', deviceId);
				}
				let browser = '微信小程序';
				let body = {};
				body.key = ChatConfig.KEY_CLIENT_BIND;
				body.timestamp = new Date().getTime();
				body.data = {};
				body.data.uid = account;
				body.data.channel = ChatConfig.APP_CHANNEL;
				body.data.appVersion = ChatConfig.APP_VERSION;
				body.data.packageName = ChatConfig.APP_PACKAGE;
				body.data.deviceId = deviceId;
				body.data.deviceName = browser;
				console.log(body);
				this.sendRequest(body);
			},

			sendRequest: function(body) {
				let data = {};
				data.type = ChatConfig.SENT_BODY;
				data.content = JSON.stringify(body);
				this.sendSocketMessage(JSON.stringify(data));
			},

			innerOnMessageReceived(e) {
				console.log(e);
				let data = JSON.parse(e.data);
				let type = data.type;
				let body = data.content;
				if (type === ChatConfig.PING) {
					this.pong();
					return;
				}
				if (type === ChatConfig.MESSAGE) {
					let message = JSON.parse(body);
					this.onInterceptMessageReceived(message);
					return;
				}
				if (type === ChatConfig.REPLY_BODY) {
					let reply = JSON.parse(body);
					/*
					 * 判断是否是握手鉴权失败
					 * 终止后续自动重连
					 */
					if (reply.key === ChatConfig.KEY_HANDSHAKE && reply.code === ChatConfig.CODE_UNAUTHORIZED) {
						this.manualStop = true
					}
					this.onReplyReceived(reply);
				}
			},

			pong: function() {
				let data = {};
				data.type = ChatConfig.PONG;
				data.content = ChatConfig.PONG_BODY;
				this.sendSocketMessage(JSON.stringify(data));
			},

			onInterceptMessageReceived(message) {
				/*
				 *被强制下线之后，不再继续连接服务端
				 */
				if (message.action === ChatConfig.ACTION_999) {
					this.manualStop = true
				}
				/*
				 *收到消息后，将消息发送给页面
				 */
				this.onMessageReceived(message);
			},

			onReplyReceived(reply) {
				console.log(reply);
				if (reply.key === ChatConfig.KEY_CLIENT_BIND && reply.code === ChatConfig.CODE_OK) {
					console.log('登录成功');
					// hideProcess();

					// $('#LoginDialog').fadeOut();

					// $('#MessageDialog').fadeIn();
					// $('#MessageDialog').addClass("in");
					// $("#current_account").text($('#account').val());
				}

				/**
				 * 链接鉴权失败
				 */
				if (reply.key === ChatConfig.KEY_HANDSHAKE && reply.code === ChatConfig.CODE_UNAUTHORIZED) {
					//hideProcess();
					console.log('鉴权失败');
				}
			},

			onMessageReceived(message) {
				console.log('message---------------', message);
				if (message.action === ChatConfig.ACTION_999) {
					console.log('强制关闭');
					return;
				}
				if (parseInt(message.sender) == this.touserid) {
					var list = [];
					list = this.newsList;
					var time = new Date(message.timestamp).toLocaleString();
					let extra = JSON.parse(message.extra);
					let cou_cont = message.content;
					
					if (extra.MessageType == 9) {
						cou_cont = JSON.parse(message.content)
						// 接受底价消息
						let list = this.newsList;
						let h_list = this.historyList;
						list.forEach(item => {
							if (extra.MsgNo == item.MsgNo) {
								item.Msg.discount_price = cou_cont.discount_price
								item.Msg.showprice = cou_cont.showprice
							}
						})
						h_list.forEach(item => {
							if (extra.MsgNo == item.MsgNo) {
								item.Msg.discount_price = cou_cont.discount_price
								item.Msg.showprice = cou_cont.showprice
							}
						})
						this.newsList = list;
						this.historyList = h_list;
					} else {
						if (extra.MessageType == 5 || extra.MessageType == 6 || extra.MessageType == 8) {
							cou_cont = JSON.parse(message.content);
							if (extra.MessageType == 5) {
								cou_cont.begintime = cou_cont.begintime.slice(0, 10);
								cou_cont.endtime = cou_cont.endtime.slice(0, 10);
							}
						}
						var _data = {
							mes_From: 'left',
							date: time,
							Msg: cou_cont,
							ReadStatus: extra.MessageType == 3 ? 0 : 1,
							MsgNo: extra.MsgNo,
							MessageType: extra.MessageType,
							shichang: extra.shichang
						};
						list.push(_data);
						console.log('list----------------', list);
						this.newsList = list
						this.scrollBottom();
					}
				}
			},

			innerOnConnectionClosed: function(e) {
				var that = this;
				if (!that.manualStop) {
					let time = Math.floor(Math.random() * 16 + 15);
					setTimeout(function() {
						console.log('Socket重新连接');
						that.connectWebSocket(); //重新连接
					}, time);
				}
			},

			generateUUID() {
				let d = new Date().getTime();
				let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					let r = (d + Math.random() * 16) % 16 | 0;
					d = Math.floor(d / 16);
					return (c === 'x' ? r : (r & 3) | 8).toString(16);
				});
				return uuid.replace(/-/g, '');
			},

			// 发送WebSocket消息
			sendSocketMessage: function(message) {
				let socket = this.socket;
				if (this.socketOpen) {
					// #ifdef MP-TOUTIAO
					socket.send({
						data: message
					});
					// #endif
					// #ifdef MP-WEIXIN
					uni.sendSocketMessage({
						data: message
					});
					// #endif
				} else {
					this.socketMsgQueue.push(message);
				}
			},

			// 关闭需求卡片
			closeXuqiu() {
				this.isSendXuqiu = false
			},

			// 发送需求卡片
			handleSendXuqiu() {
				let {
					xuqiuObj
				} = this;
				let cont = JSON.stringify(xuqiuObj);
				console.log('cont====', cont);
				var _this = this;
				var list = [];
				list = _this.newsList;
				var temp = {
					mes_From: 'right',
					Msg: xuqiuObj,
					date: new Date(),
					MessageType: 6
				};
				list.push(temp);
				this.newsList = list
				this.scrollBottom();
				http.post(
					api.default, {
						data: {
							action: 'sendmessage',
							sender: _this.userId,
							receiver: _this.touserid,
							MessageType: 6,
							content: cont
						}
					},
					false
				).then((res) => {
					this.isSendXuqiu = false
				});
			},

			goxuqiuDetai(e) {
				const data = e.currentTarget.dataset || e.target.dataset;
				if (data.xqid) {
					wxApi.navigateTo(getPage.xuqiudetail, {
						id: data.xqid
					});
				}
			},

			// 获取历史记录
			getHistory: async function() {
				var {
					touserid,
					userId,
					pageNo
				} = this;
				console.log('+++++++++++++++++', this.userId);
				console.log(this.userId, '........................');
				const res = await http.post(api.default, {
					data: {
						action: 'getmessage',
						pageIndex: pageNo,
						touserid,
						userid: userId
					}
				});
				console.log('历史数据列表：', res);
				let historyList = this.historyList;
				let res_list = res.data.data.list;
				res_list.forEach((item) => {
					if (item.MessageType == 5 || item.MessageType == 6 || item.MessageType == 8) {
						item.Msg = JSON.parse(item.Msg);
						if (item.MessageType == 5) {
							if (item.Msg.begintime) {
								item.Msg.begintime = item.Msg.begintime.slice(0, 10);
							}
							if (item.Msg.endtime) {
								item.Msg.endtime = item.Msg.endtime.slice(0, 10);
							}
						}
					}
				});
				let resList = res_list?.reverse() || [];
				for (var i = 0; i < resList.length; i++) {
					resList[i]['mes_From'] = touserid == resList[i]['FromUserId'] ? 'left' : 'right';
				}
				this.historyList = [...resList, ...historyList]
			},

			// 查看图片
			onPreviewImage(e) {
				const data = e.currentTarget.dataset || e.target.dataset;
				const {
					historyList,
					newsList
				} = this;
				console.log(data.url);
				const imgList = historyList.concat(newsList).filter((item) => item.MessageType == 2);
				const urls = imgList.map((item) => item.Msg);
				uni.previewImage({
					urls: urls,
					current: data.url,
					fail() {
						uni.showToast({
							title: '预览图片失败',
							icon: 'none'
						});
					}
				});
			},

			// 滚动到底部
			scrollBottom: function(isHis = false) {
				var {
					newsList,
					historyList
				} = this;
				var scrollid = isHis ? `historyscrollid${historyList.length - 1}` : `scrollid${newsList.length - 1}`;
				setTimeout(() => {
					this.scrollid = scrollid
					console.log('执行滑动到底部~');
				}, 1);
			},

			// 设置滚动区域的高度
			setScrollHeight: function() {
				const client = uni.getSystemInfoSync().windowHeight; // 获取当前窗口的高度
				console.log('设置滚动区域的高度', client);
				var scrollHeight = client;
				this.scrollHeight = scrollHeight
			},

			// 获取内存中聊天列表的用户信息
			getStorageBaseInfo: function() {
				//获取存储信息
				uni.getStorage({
					key: 'receivebaseInfo',
					success: (res) => {
						this.receivebaseInfo = res.data
					}
				});
			},

			// 自定义下拉刷新
			refresh: function() {
				// 下拉的实际操作
				var pageNo = this.pageNo + 1;
				this.pageNo = pageNo
				if (this.timer) {
					clearTimeout(this.timer);
				}
				this.timer = setTimeout(() => {
					this.triggered = false
					// this.getHistory();
				}, 1000);
			},

			gotoxtchat() {
				wxApi.navigateTo(getPage.xtchat, {
					id: this.id
				});
			},

			gototxl() {
				wxApi.navigateTo(getPage.txlbook, {
					id: this.id
				});
			},

			/**
			 * 返回上一页
			 */
			goBackTap() {
				//存在上一页,关闭当前返回一层,//没有上一页，跳回首页
				this.getPages > 1 ? wxApi.navigateBack(1) : wxApi.switchTab(getPage.home);
			},

			// 清空消息
			uppdatereadmsg() {
				http.post(
					api.default, {
						data: {
							action: 'uppdatereadmsg',
							userid: this.userId,
							touserid: this.touserid
						}
					},
					false
				).then((res) => {});
			},

			// 交换电话
			sendJhPhone() {
				var _this = this;
				console.log(_this);
				console.log(_this.userId);
				console.log(_this.touserid);
				var list = [];
				list = _this.newsList;
				var temp = {
					mes_From: 'right',
					date: new Date(),
					MessageType: 4
				};
				list.push(temp);
				this.newsList = list
				this.scrollBottom();
				let sendArr = this.newsList;
				http.post(
					api.default, {
						data: {
							action: 'sendmessage',
							sender: _this.userId,
							receiver: _this.touserid,
							MessageType: 4,
							content: ''
						}
					},
					false
				).then((res) => {
					this.inputtext = ''
					sendArr.forEach((item, index) => {
						if (index + 1 == sendArr.length) {
							item.MsgNo = res.data.data;
						}
					});
					this.newsList = sendArr
				});
			},

			// 同意
			agreePhone(e) {
				let MsgNo = e.currentTarget.dataset.msgno;
				this.handleJhPhone(1, MsgNo);
			},

			// 拒绝
			refusePhone(e) {
				let MsgNo = e.currentTarget.dataset.msgno;
				this.handleJhPhone(2, MsgNo);
			},

			// 同意/拒绝请求
			handleJhPhone(type, MsgNo) {
				let _this = this;
				console.log('MsgNo==', MsgNo);
				http.post(
					api.default, {
						data: {
							action: 'replymobile',
							senderid: this.touserid,
							reciverid: this.userId,
							type: type,
							MsgNo: MsgNo
						}
					},
					false
				).then((res) => {
					var list = [];
					list = _this.newsList;
					var h_list = [];
					h_list = _this.historyList;
					var temp = {
						mes_From: 'right',
						Msg: res.data.data,
						date: new Date(),
						MessageType: 0
					};
					list.push(temp);
					// 同意/拒绝后不可再次操作次条
					list.forEach((item) => {
						if (MsgNo == item.MsgNo) {
							item.isAgree = type;
						}
					});
					h_list.forEach((item) => {
						if (MsgNo == item.MsgNo) {
							item.isAgree = type;
						}
					});
					this.newsList = list
					this.historyList = h_list
					this.scrollBottom();
				});
			},

			// 发送消息
			send: function() {
				var that = this;
				console.log(that);
				console.log(that.userId);
				console.log(that.touserid);
				if (that.inputtext) {
					var list = [];
					list = that.newsList;
					var temp = {
						mes_From: 'right',
						Msg: that.inputtext,
						date: new Date(),
						MessageType: 0,
						sendType: 'loading'
					};
					list.push(temp);
					this.newsList = list
					this.scrollBottom();
					//  表情选择隐藏
					this.emotionVisible = false
					this.moreVisible = false
					let sendArr = this.newsList;
					http.post(
							api.default, {
								data: {
									action: 'sendmessage',
									sender: that.userId,
									receiver: that.touserid,
									MessageType: 0,
									content: that.inputtext
								}
							},
							false
						)
						.then((res) => {
							this.inputtext = ''
							sendArr.forEach((item) => {
								if (item.sendType == 'loading') {
									item.sendType = 'success';
								}
							});
							this.newsList = sendArr
							// let that = this;
							// setTimeout(()=>{
							//   sendArr.forEach(item=>{
							//     if(item.sendType == 'success'){
							//       item.sendType = ''
							//     }
							//   })
							//   that.setData({
							//     newsList: sendArr
							//   })
							// },500)
						})
						.catch((err) => {
							this.inputtext = ''
							sendArr.forEach((item) => {
								if (item.sendType == 'loading') {
									item.sendType = 'error';
								}
							});
							this.newsList = sendArr
						});
					// wx.sendSocketMessage({
					//   data: _this.data.input,
					//   success: (res) => {
					//     console.log(res)
					//   },
					//   fail: (err) => {
					//     console.log('sendSocketMessage', '失败')
					//   }
					// })
				}
				const client = uni.getSystemInfoSync().windowHeight; // 获取当前窗口的高度
				console.log(client, 'shurugaodu');
			},

			bindChange: function(res) {
				this.inputtext = res.detail.value
			},

			back: function() {
				// #ifdef MP-WEIXIN
				uni.closeSocket();
				// #endif
				
				// #ifdef MP-TOUTIAO
				this.socket.close()
				// #endif
				console.log('连接断开');
			},

			// 打开表情选择
			emotionChange: function() {
				uni.hideKeyboard();
				this.emotionVisible = !this.emotionVisible
			},

			// 打开更多选择
			moreChange: function() {
				uni.hideKeyboard();
				this.moreVisible = !this.moreVisible
			},

			bindChange_text: function() {
				this.is_audio = !this.is_audio
			},

			bindChange_audio: function() {
				var that = this;
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.record']) {
							uni.authorize({
								scope: 'scope.record',
								success() {
									// 用户已同意授权
									console.log('用户已同意授权');
									that.is_audio = !that.is_audio
								},
								fail() {
									// 用户拒绝了授权
									console.log('用户拒绝了授权');
									uni.showModal({
										title: '提示',
										content: '需要获取录音权限，请点击确定进入设置页面进行授权。',
										showCancel: false,
										success(res) {
											if (res.confirm) {
												uni.openSetting({
													success(res) {
														console.log(res.authSetting);
														// 用户在设置页面设置了录音权限
														if (res.authSetting[
																'scope.record']) {
															console.log(
																'用户在设置页面设置了录音权限');
															that.is_audio = !that
																.is_audio
														} else {
															console.log(
																'用户在设置页面未设置录音权限');
														}
													}
												});
											}
										}
									});
								}
							});
						} else {
							// 已经有录音权限
							console.log('已经有录音权限');
							that.is_audio = !that.is_audio
						}
					}
				});
			},

			// 去产品详情
			goproductdetail(id) {
				if (id) {
					wxApi.navigateTo(getPage.productdetail, {
						id
					});
				}
			},

			handleSetDisprice() {
				let {
					setdisprice,
					set_msgno
				} = this;
				this.chajia(set_msgno, setdisprice);
				this.$refs.setDiscountRef.close();
				this.set_msgno = '';
				this.setdisprice = '';
			},

			// 查价
			handleChajia(msgno, disprice) {
				console.log('-----------', msgno, disprice);
				if (disprice > 0) {
					this.chajia(msgno, disprice);
				} else {
					this.$refs.setDiscountRef.open();
					this.set_msgno = msgno;
				}
			},

			chajia(msgno, disprice) {
				http.post(
					api.default, {
						data: {
							action: 'updatediscount_price',
							discount_price: disprice,
							msgno: msgno
						}
					},
					false
				).then((res) => {
					var list = this.newsList;
					var h_list = this.historyList;
					list.forEach((item) => {
						if (msgno == item.MsgNo) {
							item.Msg.showprice = true;
							item.Msg.discount_price = disprice;
						}
					});
					h_list.forEach((item) => {
						if (msgno == item.MsgNo) {
							item.Msg.showprice = true;
							item.Msg.discount_price = disprice;
						}
					});
					this.newsList = list;
					this.historyList = h_list;
				});
			},

			//  选择图片
			chooseImage: function() {
				var that = this;
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.writePhotosAlbum']) {
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success() {
									// 已经授权，可以直接选择图片
									uni.chooseMedia({
										count: 1,
										mediaType: ['image'],
										sourceType: ['album', 'camera'],
										maxDuration: 30,
										success: (res) => {
											let tempFilePathImg = res.tempFiles[0]
												.tempFilePath;
											that.uploadFile(tempFilePathImg);
										}
									});
								}
							});
						} else {
							// 已经授权，可以直接选择图片
							uni.chooseMedia({
								count: 1,
								mediaType: ['image'],
								sourceType: ['album', 'camera'],
								maxDuration: 30,
								success: (res) => {
									let tempFilePathImg = res.tempFiles[0].tempFilePath;
									that.uploadFile(tempFilePathImg);
								}
							});
						}
					}
				});
			},

			// 上传图片到服务器
			uploadFile(tempFilePathImg) {
				uni.showLoading();
				uni.uploadFile({
					filePath: tempFilePathImg,
					name: 'file',
					url: getApp().globalData.url + 'common/upload',
					formData: {
						data: 'bank_img'
					},
					success: (res) => {
						uni.hideLoading();
						const bank_img = JSON.parse(res.data).img; //把数据字符串转变成对象
						if (bank_img) {
							this.bank_img = bank_img
							this.isShow = true
						}
						this.$emit('chooseMedia', {
							detail: bank_img
						});
					}
				});
			},

			// 发送图片
			afterRead(event) {
				console.log('发送图片----------', event);
				const {
					file
				} = event.detail;
				var that = this;
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				for (var i = 0; i < file.length; i++) {
					var item = file[i];
					uploadImage({
						filePath: item.url,
						dir: 'users',
						success(res) {
							// 上传完成发送
							var img_url = api.imageCdn + res;
							console.log('api.imageCdn + res', api.imageCdn + res);
							http.post(api.default, {
								data: {
									action: 'sendmessage',
									sender: that.userId,
									receiver: that.touserid,
									MessageType: 2,
									content: img_url
								}
							}).then((res) => {
								var list = [];
								list = that.newsList;
								var temp = {
									mes_From: 'right',
									Msg: img_url,
									date: new Date(),
									MessageType: 2
								};
								list.push(temp);
								that.newsList = list,
									that.inputtext = '',
									that.moreVisible = false
								that.scrollBottom();
							});
						},
						fail(res) {
							$toast(`图片上传失败${res}`);
						}
					});
				}
			},

			// 发送视频
			afterVideoRead(event) {
				console.log('发送图片----------', event);
				const {
					file
				} = event.detail;
				var that = this;
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				for (var i = 0; i < file.length; i++) {
					var item = file[i];
					uploadImage({
						filePath: item.url,
						dir: 'users',
						success(res) {
							// 上传完成发送
							var img_url = api.imageCdn + res;
							console.log('api.imageCdn + res', api.imageCdn + res);
							http.post(api.default, {
								data: {
									action: 'sendmessage',
									sender: that.userId,
									receiver: that.touserid,
									MessageType: 7,
									content: img_url
								}
							}).then((res) => {
								var list = [];
								list = that.newsList;
								var temp = {
									mes_From: 'right',
									Msg: img_url,
									date: new Date(),
									MessageType: 7
								};
								list.push(temp);
								that.newsList = list
								that.inputtext = ''
								that.moreVisible = false
								that.scrollBottom();
							});
						},
						fail(res) {
							$toast(`图片上传失败${res}`);
						}
					});
				}
			},

			//获取优惠券列表
			async getshopcoupons() {
				let {
					ShopId
				} = this;
				if (!ShopId) return
				let res = await http.post(
					api.default, {
						data: {
							action: 'getshopcoupons',
							shopid: ShopId
						}
					},
					false
				);
				const {
					data
				} = res.data;
				console.log('getshopcoupons------------', data);
				data.forEach((cou) => {
					cou.info.begintime = cou.info.begintime.slice(0, 10);
					cou.info.endtime = cou.info.endtime.slice(0, 10);
				});
				this.couponList = data
			},

			fasongCoupon(e) {
				let cou_item = e.currentTarget.dataset.info;
				let cou_cont = JSON.stringify(cou_item);
				var _this = this;
				var list = [];
				list = _this.newsList;
				var temp = {
					mes_From: 'right',
					Msg: cou_item,
					date: new Date(),
					MessageType: 5
				};
				list.push(temp);
				this.newsList = list
				this.sendCouponBotClose();
				this.moreVisible = false
				this.scrollBottom();
				http.post(api.default, {
					data: {
						action: 'sendmessage',
						sender: _this.userId,
						receiver: _this.touserid,
						MessageType: 5,
						content: cou_cont
					}
				}).then((res) => {});
			},

			// 领取优惠券
			linquCoupon(e) {
				let _this = this;
				let {
					msgno
				} = e.currentTarget.dataset;
				http.post(api.default, {
					data: {
						action: 'getcouponfromchat',
						msgno: msgno
					}
				}).then((res) => {
					console.log('res===', res);
					let his_list = _this.historyList;
					let new_list = _this.newsList;
					new_list.forEach((item) => {
						if (msgno == item.MsgNo) {
							item.Msg.isreceived = true;
						}
					});
					his_list.forEach((item) => {
						if (msgno == item.MsgNo) {
							item.Msg.isreceived = true;
						}
					});
					this.historyList = his_list
					this.newsList = new_list
				});
			},

			// 发送优惠券
			handelSendCoupon() {
				let _this = this;
				let {
					couponobj
				} = this;
				if (!couponobj.orderamount || !couponobj.price || !couponobj.days) {
					return $toast('请填写完整优惠券信息');
				}
				http.post(api.default, {
					data: {
						action: 'addcouponfromchat',
						shopid: _this.ShopId,
						touserid: _this.touserid,
						price: couponobj.price,
						orderamount: couponobj.orderamount,
						days: couponobj.days
					}
				}).then((res) => {
					console.log('res====', res);
					let {
						data
					} = res.data;
					let cou_cont = JSON.stringify(data);
					data.begintime = data.begintime.slice(0, 10);
					data.endtime = data.endtime.slice(0, 10);
					var list = [];
					list = _this.newsList;
					var temp = {
						mes_From: 'right',
						Msg: data,
						date: new Date(),
						MessageType: 5
					};
					list.push(temp);
					this.newsList = list
					this.sendCouponClose();
					this.moreVisible = false
					this.scrollBottom();
					http.post(api.default, {
						data: {
							action: 'sendmessage',
							sender: _this.userId,
							receiver: _this.touserid,
							MessageType: 5,
							content: cou_cont
						}
					}).then((res) => {});
				});
			},

			// 发优惠券弹窗-底部
			sendCouponPopupBottom() {
				this.$refs.sendCouponBotRefs.open();
			},

			// 发优惠券弹窗-底部-关闭
			sendCouponBotClose() {
				this.$refs.sendCouponBotRefs.close();
			},

			// 发优惠券弹窗
			sendCouponPopup() {
				this.sendCouponShow = true
			},

			// 发优惠券弹窗-关闭
			sendCouponClose() {
				this.sendCouponShow = false
				this.couponobj.orderamount = null
				this.couponobj.price = null
				this.couponobj.days = null
			},

			bindOrderamountChange(e) {
				this.couponobj.orderamount = e.detail.value
			},

			bindPriceChange(e) {
				this.couponobj.price = e.detail.value
			},

			validDayInput(e) {
				this.couponobj.days = e.detail
			},

			// 开始录音
			onStartRecord: function() {
				this.isTag = true
				const options = {
					duration: 10000,
					//指定录音的时长，单位 ms
					sampleRate: 16000,
					//采样率
					numberOfChannels: 1,
					//录音通道数
					encodeBitRate: 96000,
					//编码码率
					format: 'mp3',
					//音频格式，有效值 aac/mp3
					frameSize: 50 //指定帧大小，单位 KB
				};
				//开始录音
				recorderManager.start(options);
				recorderManager.onStart(() => {
					console.log('recorder start');
				});
				//错误回调
				recorderManager.onError((res) => {
					console.log(res);
				});
			},

			// 结束录音
			onStopRecord: function() {
				var that = this;
				recorderManager.stop();
				recorderManager.onStop((res) => {
					console.log('停止录音---时长', res);
					const {
						tempFilePath,
						duration
					} = res;
					var shichang = Math.floor(duration / 1000);
					if (shichang < 1) {
						$toast('语音消息太短');
						this.isTag = false
						return;
					}
					uploadImage({
						filePath: tempFilePath,
						dir: 'chat',
						success(res) {
							var vio_url = api.imageCdn + res;
							http.post(api.default, {
								data: {
									action: 'sendmessage',
									sender: that.userId,
									receiver: that.touserid,
									MessageType: 3,
									content: vio_url,
									shichang: Math.floor(duration / 1000)
								}
							}).then((res) => {
								var list = [];
								list = that.newsList;
								var temp = {
									mes_From: 'right',
									Msg: vio_url,
									date: new Date(),
									MessageType: 3,
									shichang: Math.floor(duration / 1000)
								};
								list.push(temp);
								that.newsList = list
								that.inputtext = ''
								that.scrollBottom();
							});
						},
						fail(res) {
							$toast(`语音上传失败${res}`);
						}
					});
					this.isTag = false
				});
			},

			//播放声音
			onPlay: function(e) {
				const innerAudioContext = uni.createInnerAudioContext();
				var data = e.currentTarget.dataset || e.target.dataset;
				console.log('data===', data);
				this.cut_video = data.url
				innerAudioContext.autoplay = true;
				innerAudioContext.src = data.url;
				innerAudioContext.onPlay(() => {
					console.log('开始播放');
				});
				innerAudioContext.onEnded((res) => {
					console.log('播放结束', res);
					innerAudioContext.destroy();
					this.cut_video = ''
				});
				innerAudioContext.onError((res) => {
					$toast(`播放错误${res.errCode}`);
					innerAudioContext.destroy();
				});
				console.log('-----', data.status);
				if (data.status == 0) {
					http.post(api.default, {
						data: {
							action: 'updatemsgreadstatusbyno',
							no: data.no,
							status: 1
						}
					}).then(() => {
						let hisArr = this.historyList;
						hisArr.forEach((item) => {
							if (item.MsgNo == data.no) {
								item.ReadStatus = 1;
							}
						});
						let newArr = this.newsList;
						newArr.forEach((item) => {
							if (item.MsgNo == data.no) {
								item.ReadStatus = 1;
							}
						});
						thia.historyList = hisArr
						thia.newsList = newArr
					});
				}
			},

			//点击发送表情
			addemotion: function(e) {
				var that = this;
				// 点击的表情
				var url = e.currentTarget.dataset.index.url;
				// 拼接的url
				var resurl = this.imageCdn + 'bq/' + url;
				http.post(api.default, {
					data: {
						action: 'sendmessage',
						sender: that.userId,
						receiver: that.touserid,
						MessageType: 1,
						content: resurl
					}
				}).then((res) => {
					var list = [];
					list = that.newsList;
					var temp = {
						mes_From: 'right',
						Msg: resurl,
						date: new Date(),
						MessageType: 1
					};
					list.push(temp);
					this.newsList = list
					this.inputtext = ''
					this.scrollBottom();
					//  表情选择隐藏
					this.emotionVisible = false
				});
			},

			// 公共聚焦方法，方法比较笨，但是过度效果平滑流畅
			bottom: function() {
				var that = this;

				// 获取元素的高度
				let query = uni.createSelectorQuery();
				query
					.select('.news')
					.boundingClientRect((rect) => {
						//获取到元素
						let scrollTop = rect.height;
						this.scrollTop = scrollTop
					})
					.exec();
				console.log(this.scrollTop, 'hahah');
				uni.pageScrollTo({
					// scrollTop: this.data.scrollTop + 30,
					scrollTop: 10000
					// duration: 0
				});
			}
		}
	}
</script>

<style lang="scss">
	@import './chat.css';
</style>
